﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace cls.u_Models
{
    public partial class ShowIssuseplu : System.Web.UI.Page
    {
        static String UserName = "";
        static String OrgCode = "";
        static String UserInOrgCode = "";
        static String UserInOrgId = "";
        static Boolean UserInZB = false;
        static Boolean HiddenClsRespons = false;

        //ClsRepons的DropDownList组件
        //static DropDownList DropDownListClsRepons = new DropDownList();
        //void DropDownList_ShowClsRepons();

        protected void Page_Load(object sender, EventArgs e)
        {
            //Cls的List形式
            //DropDownList_ShowClsRepons();

            UserName = User.Identity.Name;

            if (UserName.Equals(""))
            {
                Response.Redirect("..\\Default.aspx");
            }
            else
            {
                UserInOrgCode = GetOrgCodeByUserName(UserName);
                UserInOrgId = GetOrgIdByUserName(UserName);
            }

            if (UserInOrgCode.Trim().Equals("ZB"))
            {
                OrgCode = "all";
                UserInZB = true;

                //ClsRepons的DropDownList组件
                //DropDownList_ShowClsRepons();
            }
            else
            {
                OrgCode = UserInOrgCode;
                UserInZB = false;
            }

            if (!Page.IsPostBack)
            {
                //IssusepluDetailDataBind(UserInOrgCode);
                DropDownList_ShowOrgNames();
                //Label_HiddenClsRespons.Visible = UserInZB;
                CheckBox_HiddenClsRespons.Visible = UserInZB;
            }

            //Button_Export.Enabled = false;
            CheckBox_HiddenClsRespons.Style.Clear();
        }

        protected String GetOrgCodeByUserName(String UserName)
        {
            String OrgCode = "";

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand("SELECT OrgCode FROM u_cls_Org WHERE Id = (SELECT OrgId FROM u_cls_UserInOrg WHERE UserName = @UserName)", SqlConnection);

            SelectCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 4);
            SelectCommand.Parameters["@UserName"].Value = UserName;

            SqlDataReader OrgCodeReader = SelectCommand.ExecuteReader();

            while (OrgCodeReader.Read())
            {
                //还是分开取得比较好，后面还有单独用到OrgCode的地方......
                //OrgCode = ResReader["OrgCode"].ToString() + "-" + ResReader["OrgName"].ToString();  
                OrgCode = OrgCodeReader["OrgCode"].ToString().Trim();
            }

            OrgCodeReader.Close();
            SqlConnection.Close();

            return OrgCode;
        }

        protected String GetOrgIdByUserName(String UserName)
        {
            String OrgId = "";

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand("SELECT [OrgId] FROM [dbo].[u_cls_UserInOrg] WHERE [UserName] = @UserName", SqlConnection);

            SelectCommand.Parameters.Add("@UserName", SqlDbType.NVarChar, 4);
            SelectCommand.Parameters["@UserName"].Value = UserName;

            SqlDataReader OrgIdReader = SelectCommand.ExecuteReader();

            while (OrgIdReader.Read())
            {
                OrgId = OrgIdReader["OrgId"].ToString().ToUpper();
            }

            OrgIdReader.Close();
            SelectCommand.Dispose();
            SqlConnection.Close();

            return OrgId;
        }

        protected String GetLastInsDatetime(String OrgCode)
        {
            String LastInsDatetime = "";
            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand("SELECT TOP(1) LastInsDatetime FROM [dbo].[u_cls_LastInsDatetime] WHERE ApplicationName = 'Issuseplu' AND OrgCode = @OrgCode ORDER BY LastInsDatetime DESC", SqlConnection);

            SelectCommand.Parameters.Add("@OrgCode", SqlDbType.NVarChar, 4);
            SelectCommand.Parameters["@OrgCode"].Value = OrgCode;

            SqlDataReader LastInsDatetimeReader = SelectCommand.ExecuteReader();

            //酱紫写法系错误嘀，乖乖的用While循环吧......
            //if(LastInsDatetimeReader.HasRows)
            //{
            //    LastInsDatetime = LastInsDatetimeReader["LastInsDatetime"].ToString();
            //}
            while (LastInsDatetimeReader.Read())
            {
                LastInsDatetime = LastInsDatetimeReader["LastInsDatetime"].ToString();
            }

            LastInsDatetimeReader.Close();
            SqlConnection.Close();

            return LastInsDatetime;
        }

        protected void DropDownList_ShowOrgNames()
        {
            DropDownList_SelectOrgCode.Items.Clear();

            String SelectCommandString = "";

            if (UserInOrgCode.Trim().Equals("ZB"))
            {
                DropDownList_SelectOrgCode.Items.Add(new ListItem("全部", "all"));
                SelectCommandString = "SELECT OrgCode,OrgName FROM [dbo].[u_cls_Org] ORDER BY OrgCode";
            }
            else
            {
                SelectCommandString = "SELECT OrgCode,OrgName FROM [dbo].[u_cls_Org] WHERE Id = '" + UserInOrgId + "' ORDER BY OrgCode";
            }

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand SelectCommand = new SqlCommand(SelectCommandString, SqlConnection);
            SqlDataReader OrgCodeReader = SelectCommand.ExecuteReader();

            while (OrgCodeReader.Read())
            {
                DropDownList_SelectOrgCode.Items.Add(new ListItem(OrgCodeReader["OrgCode"].ToString() + "-" + OrgCodeReader["OrgName"].ToString(), OrgCodeReader["OrgCode"].ToString()));
            }

            OrgCodeReader.Close();
            SelectCommand.Dispose();
            SqlConnection.Close();
        }

        //ClsRepons的DropDownList形式
        //退仓
        //报废
        //退仓转正品仓
        //打折3
        //打折5
        //打折7
        //继续售卖
        //做促销
        protected void DropDownList_ShowClsRepons()
        {
            String[] ClsReponsString = { "退仓", "报废", "退仓转正品仓", "打折3", "打折5", "打折7", "继续售卖", "做促销" };
            //DropDownListClsRepons.DataSource = ClsReponsString;
            //DropDownListClsRepons.DataValueField
            //DropDownListClsRepons.DataBind();
            //DropDownListClsRepons = new DropDownList();
            //DropDownListClsRepons.Items.Add(new ListItem("退仓", "退仓"));
            //DropDownListClsRepons.Items.Add(new ListItem("报废", "报废"));
            //DropDownListClsRepons.Items.Add(new ListItem("退仓转正品仓", "退仓转正品仓"));
            //DropDownListClsRepons.Items.Add(new ListItem("打折3", "打折3"));
            //DropDownListClsRepons.Items.Add(new ListItem("打折5", "打折5"));
            //DropDownListClsRepons.Items.Add(new ListItem("打折7", "打折7"));
            //DropDownListClsRepons.Items.Add(new ListItem("继续售卖", "继续售卖"));
            //DropDownListClsRepons.Items.Add(new ListItem("做促销", "做促销"));
        }

        protected DataSet IssusepluDetailDateSet(String OrgCode, String LastInsDatetime)
        {
            DataSet IssusepluDetailDateSet = new DataSet();

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            //ImportDatetime的毫秒为0，LastInsDatetime的毫秒不是0
            //导致查询没有结果
            //String SelectCommandString = "SELECT [id],[OrgCode],[OrgName],[PluCode],[PluName],[Spec],[RetCount],[InvCount],[RetReason],[ClsRepons],[ProDate],[ExpDate],[ImportDatetime],[ImportUserName] FROM [dbo].[u_cls_Issuseplu_Table] WHERE [ImportDatetime] = '" + LastInsDatetime + "'";

            //使用SQL Server的MAX()函数重新构建语句
            //下面是正确的语句
            String SelectCommandString = "SELECT [id],[u_cls_Issuseplu_Table].[OrgCode],[OrgName],[PluCode],[PluName],[Spec],[RetCount],[InvCount],[RetReason],[ClsRepons],[ProDate],[ExpDate],[dbo].[u_cls_Issuseplu_Table].[ImportDatetime],[ImportUserName] FROM [dbo].[u_cls_Issuseplu_Table] JOIN(SELECT OrgCode,MAX(ImportDatetime) AS ImportDatetime FROM [u_cls_Issuseplu_Table] GROUP BY OrgCode) t ON [u_cls_Issuseplu_Table].[OrgCode] = t.[OrgCode] AND [u_cls_Issuseplu_Table].[ImportDatetime] = t.ImportDatetime";

            //是否选择了OrgCode
            if (OrgCode.Equals("all"))
            { }
            else
            {
                //SelectCommandString += " AND OrgCode='" + OrgCode + "'";
                SelectCommandString += " WHERE [u_cls_Issuseplu_Table].[OrgCode] ='" + OrgCode + "'";
            }

            //是否隐藏已经回复的行
            if (CheckBox_HiddenClsRespons.Checked)
            {
                SelectCommandString += " AND [u_cls_Issuseplu_Table].[ClsRepons] = ''";
            }

            SelectCommandString += " ORDER BY [u_cls_Issuseplu_Table].[OrgCode],[u_cls_Issuseplu_Table].[PluCode]";

            SqlDataAdapter dataAdapter = new SqlDataAdapter(SelectCommandString, SqlConnection);
            dataAdapter.Fill(IssusepluDetailDateSet);

            dataAdapter.Dispose();
            SqlConnection.Close();

            return IssusepluDetailDateSet;
        }

        protected void IssusepluDetailDataBind(String OrgCode)
        {
            GridView_Issuseplu.AutoGenerateColumns = false;
            GridView_Issuseplu.Columns.Clear();

            GridView_Issuseplu.DataSource = IssusepluDetailDateSet(OrgCode, GetLastInsDatetime(UserInOrgCode));
            GridView_Issuseplu.DataKeyNames = new string[] { "id" };

            BoundField bField;

            bField = new BoundField();
            bField.DataField = "id";
            bField.HeaderText = "编号";
            bField.ReadOnly = true;
            bField.Visible = false;
            GridView_Issuseplu.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "OrgCode";
            bField.HeaderText = "组织编码";
            bField.ReadOnly = true;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Issuseplu.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "OrgName";
            bField.HeaderText = "组织名称";
            bField.ReadOnly = true;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Issuseplu.Columns.Add(bField);

            //[3]
            bField = new BoundField();
            bField.DataField = "PluCode";
            bField.HeaderText = "商品编码";
            bField.ReadOnly = true;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Issuseplu.Columns.Add(bField);

            //[4]
            bField = new BoundField();
            bField.DataField = "PluName";
            bField.HeaderText = "商品名称";
            bField.ReadOnly = true;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            GridView_Issuseplu.Columns.Add(bField);

            //[5]
            bField = new BoundField();
            bField.DataField = "Spec";
            bField.HeaderText = "商品规格";
            bField.ReadOnly = true;
            //bField.DataFormatString = "{0:D}";
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Issuseplu.Columns.Add(bField);

            //[6]
            bField = new BoundField();
            bField.DataField = "RetCount";
            bField.HeaderText = "退货数量";
            bField.ReadOnly = true;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Issuseplu.Columns.Add(bField);

            //[7]
            bField = new BoundField();
            bField.DataField = "InvCount";
            bField.HeaderText = "库存数量";
            bField.ReadOnly = true;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Issuseplu.Columns.Add(bField);

            //[8]
            bField = new BoundField();
            bField.DataField = "RetReason";
            bField.HeaderText = "退货说明";
            bField.ReadOnly = UserInZB;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Left;
            GridView_Issuseplu.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "ProDate";
            bField.HeaderText = "生产日期";
            bField.ReadOnly = UserInZB;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Issuseplu.Columns.Add(bField);

            bField = new BoundField();
            bField.DataField = "ExpDate";
            bField.HeaderText = "到期日期";
            bField.ReadOnly = UserInZB;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Issuseplu.Columns.Add(bField);

            //[11]
            bField = new BoundField();
            bField.DataField = "ClsRepons";
            bField.HeaderText = "品类回复";
            bField.ReadOnly = !UserInZB;
            bField.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            bField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Issuseplu.Columns.Add(bField);

            //RetReason的List形式
            //参考资料
            //http://blog.sina.com.cn/s/blog_492faa8f0100di5x.html
            //http://msdn.microsoft.com/en-us/library/aa479353.aspx
            //http://msdn.microsoft.com/zh-cn/library/ms178294(v=vs.100).aspx
            //DropDownList或者ListBox形式
            //TemplateField tField = new TemplateField();
            //tField.ItemTemplate.InstantiateIn("?");
            //tField.EditItemTemplate.InstantiateIn(DropDownListClsRepons);
            //tField.HeaderText = "品类回复";
            //GridView_Issuseplu.Columns.Add(tField);            

            if (UserInZB)
            {
                //bField = new BoundField();
                //bField.DataField = "LastModifyDatetime";
                //bField.HeaderText = "最后修改时间";
                //bField.ReadOnly = true;
                //GridView_Issuseplu.Columns.Add(bField);

                bField = new BoundField();
                bField.DataField = "ImportDatetime";
                bField.HeaderText = "上传时间";
                bField.ReadOnly = true;
                GridView_Issuseplu.Columns.Add(bField);

                bField = new BoundField();
                bField.DataField = "ImportUserName";
                bField.HeaderText = "上传用户";
                bField.HeaderStyle.Wrap = false;
                bField.ItemStyle.Wrap = false;
                bField.ReadOnly = true;
                GridView_Issuseplu.Columns.Add(bField);
            }

            CommandField cfEdit = new CommandField();
            cfEdit.ButtonType = ButtonType.Link;
            cfEdit.EditText = "编辑";
            cfEdit.ShowEditButton = true;
            cfEdit.UpdateText = "更新";
            cfEdit.CancelText = "取消";
            //cfEdit.DeleteText = "删除";
            cfEdit.ItemStyle.Wrap = false;
            GridView_Issuseplu.Columns.Add(cfEdit);

            //无效
            //GridView_Issuseplu.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            GridView_Issuseplu.HeaderStyle.Font.Size = 8;

            GridView_Issuseplu.DataBind();

            //显示页脚合计
            GridView_Issuseplu_CosFooter();
        }

        protected void GridView_Issuseplu_CosFooter()
        {
            if (GridView_Issuseplu.Rows.Count > 0)
            {
                //Decimal _StdCount = 0m;
                //Decimal _ExiCount = 0m;
                //Decimal _DepCount = 0m;

                //退货数量合计
                Decimal _RetCount = 0m;
                //库存数量合计
                Decimal _InvCount = 0m;

                //
                //Decimal _NdCount = 0m;

                for (int i = 0; i < GridView_Issuseplu.Rows.Count; i++)
                {
                    if (GridView_Issuseplu.Rows[i].RowType == DataControlRowType.DataRow)
                    {
                        //_StdCount += Convert.ToDecimal(GridView_Issuseplu.Rows[i].Cells[3].Text);
                        //_ExiCount += Convert.ToDecimal(GridView_Issuseplu.Rows[i].Cells[4].Text);
                        //_DepCount += Convert.ToDecimal(GridView_Issuseplu.Rows[i].Cells[5].Text);
                        _RetCount += Convert.ToDecimal(GridView_Issuseplu.Rows[i].Cells[6].Text);
                        _InvCount += Convert.ToDecimal(GridView_Issuseplu.Rows[i].Cells[7].Text);
                        //_NdCount += Convert.ToDecimal(GridView_Issuseplu.Rows[i].Cells[8].Text);
                    }
                }

                GridView_Issuseplu.FooterRow.Cells[1].Wrap = false;
                GridView_Issuseplu.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Center;
                GridView_Issuseplu.FooterRow.Cells[1].Text = "合计：";
                //GridView_Issuseplu.FooterRow.Cells[3].HorizontalAlign = HorizontalAlign.Center;
                //GridView_Issuseplu.FooterRow.Cells[3].Text = _StdCount.ToString();
                //GridView_Issuseplu.FooterRow.Cells[4].HorizontalAlign = HorizontalAlign.Center;
                //GridView_Issuseplu.FooterRow.Cells[4].Text = _ExiCount.ToString();
                //GridView_Issuseplu.FooterRow.Cells[5].HorizontalAlign = HorizontalAlign.Center;
                //GridView_Issuseplu.FooterRow.Cells[5].Text = _DepCount.ToString();
                GridView_Issuseplu.FooterRow.Cells[6].HorizontalAlign = HorizontalAlign.Center;
                GridView_Issuseplu.FooterRow.Cells[6].Text = _RetCount.ToString();
                GridView_Issuseplu.FooterRow.Cells[7].HorizontalAlign = HorizontalAlign.Center;
                GridView_Issuseplu.FooterRow.Cells[7].Text = _InvCount.ToString();
                //GridView_Issuseplu.FooterRow.Cells[8].HorizontalAlign = HorizontalAlign.Center;
                //GridView_Issuseplu.FooterRow.Cells[8].Text = _NdCount.ToString();
            }
        }

        protected void GridView_Issuseplu_RowEditing(object sender, GridViewEditEventArgs e)
        {
            //Set the edit index.
            GridView_Issuseplu.EditIndex = e.NewEditIndex;

            //RetReason的List形式
            //参考资料
            //http://blog.sina.com.cn/s/blog_492faa8f0100di5x.html
            //http://msdn.microsoft.com/en-us/library/aa479353.aspx
            //http://msdn.microsoft.com/zh-cn/library/ms178294(v=vs.100).aspx

            //Bind data to the GridView control. 
            //必须
            UserInOrgCode = DropDownList_SelectOrgCode.SelectedValue;
            IssusepluDetailDataBind(UserInOrgCode);
        }

        protected void GridView_Issuseplu_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            //不是必须赋值
            //如用户删除TextBox内文本，会造成ClsCode = ""。
            //OrgCode = DropDownList_SelectOrgCode.SelectedValue;
            //ClsCode = TextBox_InputClsCode.Text;
            //PluCode = TextBox_InputPluCode.Text;

            //Reset the edit index.
            GridView_Issuseplu.EditIndex = -1;

            //Bind data to the GridView control.
            UserInOrgCode = DropDownList_SelectOrgCode.SelectedValue;
            IssusepluDetailDataBind(UserInOrgCode);
        }

        protected void GridView_Issuseplu_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            String id = GridView_Issuseplu.DataKeys[e.RowIndex]["id"].ToString();
            String RetReason = null;
            String ClsRepons = null;

            //String RetCount = ((TextBox)GridView_Issuseplu.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
            //String DepCount = ((TextBox)GridView_Issuseplu.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
            //String NcCount = ((TextBox)GridView_Issuseplu.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
            //String NtCount = ((TextBox)GridView_Issuseplu.Rows[e.RowIndex].Cells[6].Controls[0]).Text;
            //String NdCount = ((TextBox)GridView_Issuseplu.Rows[e.RowIndex].Cells[7].Controls[0]).Text;

            if (UserInZB)
            {
                ClsRepons = ((TextBox)GridView_Issuseplu.Rows[e.RowIndex].Cells[11].Controls[0]).Text;
            }
            else
            {
                RetReason = ((TextBox)GridView_Issuseplu.Rows[e.RowIndex].Cells[8].Controls[0]).Text;
            }

            GridView_Issuseplu_RowUpdate(UserInZB, id, RetReason, ClsRepons);

            //Reset the edit index.
            GridView_Issuseplu.EditIndex = -1;

            //返回所选择的门店查询结果
            UserInOrgCode = DropDownList_SelectOrgCode.SelectedValue;
            IssusepluDetailDataBind(UserInOrgCode);
        }

        protected void GridView_Issuseplu_RowUpdate(Boolean UserInZB, String id, String RetReason, String ClsRepons)
        {
            DateTime LastModifyDatetime = DateTime.Now;

            SqlConnection SqlConnection = new SqlConnection("Data Source=192.168.0.241;Initial Catalog=cls_forms_db;Persist Security Info=True;User ID=sa;Password=My.SA");
            SqlConnection.Open();

            SqlCommand UpdateCommand = new SqlCommand();

            String UpdateString = "";
            if (UserInZB)
            {
                UpdateString = "UPDATE [dbo].[u_cls_Issuseplu_Table] SET [ClsRepons] = @ClsRepons WHERE [Id] = @Id";
                UpdateCommand.CommandText = UpdateString;
                UpdateCommand.CommandType = CommandType.Text;
                UpdateCommand.Connection = SqlConnection;

                UpdateCommand.Parameters.Add("@id", SqlDbType.UniqueIdentifier);
                UpdateCommand.Parameters.Add("@ClsRepons", SqlDbType.NVarChar, 4000);

                //必须转换
                //Exception Details: System.InvalidCastException: Invalid cast from 'System.String' to 'System.Guid'.
                UpdateCommand.Parameters["@id"].Value = new System.Guid(id);
                UpdateCommand.Parameters["@ClsRepons"].Value = ClsRepons;

                UpdateCommand.ExecuteNonQuery();
            }
            else
            {
                UpdateString = "UPDATE [dbo].[u_cls_Issuseplu_Table] SET [RetReason] = @RetReason WHERE [Id]=@Id";
                UpdateCommand.CommandText = UpdateString;
                UpdateCommand.CommandType = CommandType.Text;
                UpdateCommand.Connection = SqlConnection;

                UpdateCommand.Parameters.Add("@id", SqlDbType.UniqueIdentifier);
                //UpdateCommand.Parameters.Add("@ExiCount", SqlDbType.Int);
                //UpdateCommand.Parameters.Add("@DepCount", SqlDbType.Int);
                //UpdateCommand.Parameters.Add("@NcCount", SqlDbType.Int);
                //UpdateCommand.Parameters.Add("@NtCount", SqlDbType.Int);
                //UpdateCommand.Parameters.Add("@NdCount", SqlDbType.Int);
                UpdateCommand.Parameters.Add("@RetReason", SqlDbType.NVarChar, 4000);
                //UpdateCommand.Parameters.Add("@LastModifyDatetime", SqlDbType.DateTime);

                UpdateCommand.Parameters["@id"].Value = new System.Guid(id);
                //UpdateCommand.Parameters["@ExiCount"].Value = Int32.Parse(RetReason);
                //UpdateCommand.Parameters["@DepCount"].Value = Int32.Parse(DepCount);
                //UpdateCommand.Parameters["@NcCount"].Value = Int32.Parse(NcCount);
                //UpdateCommand.Parameters["@NtCount"].Value = Int32.Parse(NtCount);
                //UpdateCommand.Parameters["@NdCount"].Value = Int32.Parse(NdCount);
                UpdateCommand.Parameters["@RetReason"].Value = RetReason;
                //UpdateCommand.Parameters["@LastModifyDatetime"].Value = LastModifyDatetime;
            }

            try
            {
                UpdateCommand.ExecuteNonQuery();
            }
            catch (SqlException se)
            {
                //Label_ErrorMsg.Text = se.Message;
                //Label_ErrorMsg.Visible = true;
            }

            UpdateCommand.Dispose();
            SqlConnection.Close();
        }

        protected void Button_ShowIssusePluDetail_Click(object sender, EventArgs e)
        {
            GridView_Issuseplu.EmptyDataText = "您的查询条件没有结果。";

            UserInOrgCode = DropDownList_SelectOrgCode.SelectedValue;

            IssusepluDetailDataBind(UserInOrgCode);
        }

        protected void Button_Return_Click(object sender, EventArgs e)
        {
            Response.Redirect("IssusepluMgr.aspx");
        }

        protected void Button_Export_Click(object sender, EventArgs e)
        {            
            //文件名只能是.xls，.xlsx会导致文件无法打开（Office 2013 X64）
            ExportToExcel(null, GridView_Issuseplu, UserInOrgCode + "_" + UserName + "_" + DateTime.Now + "_导出.xls");
        }

        //参考资料
        //http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
        //http://www.c-sharpcorner.com/UploadFile/DipalChoksi/exportxl_asp22_dc04022007235740PM/exportxl_asp22_dc.aspx?ArticleID=1195fe8c-c6f5-4d52-925b-953f4b9de344
        private void ExportToExcel(string FileType, GridView SourceGV, string FileName)
        {
            //参考资料
            //http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
            //http://www.cnblogs.com/sparon/archive/2007/04/06/702946.html
            //
            //Office 2007 File Format MIME Types for HTTP Content Streaming
            //http://blogs.msdn.com/b/vsofficedeveloper/archive/2008/05/08/office-2007-open-xml-mime-types.aspx
            
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", FileName));
            
            //HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    //  Create a table to contain the grid
                    Table table = new Table();

                    //  include the gridline settings
                    table.GridLines = SourceGV.GridLines;

                    //  add the header row to the table
                    if (SourceGV.HeaderRow != null)
                    {
                        ShowIssuseplu.PrepareControlForExport(SourceGV.HeaderRow);
                        table.Rows.Add(SourceGV.HeaderRow);
                    }

                    //  add each of the data rows to the table
                    foreach (GridViewRow row in SourceGV.Rows)
                    {
                        ShowIssuseplu.PrepareControlForExport(row);
                        table.Rows.Add(row);
                    }

                    //  add the footer row to the table
                    if (SourceGV.FooterRow != null)
                    {
                        ShowIssuseplu.PrepareControlForExport(SourceGV.FooterRow);
                        table.Rows.Add(SourceGV.FooterRow);
                    }

                    //  render the table into the htmlwriter
                    table.RenderControl(htw);

                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }            
        }

        private static void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                if (current.HasControls())
                {
                    ShowIssuseplu.PrepareControlForExport(current);
                }
            }
        }

        protected void GridView_Issuseplu_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridView_Issuseplu.SelectedRow.Focus();
        }

        //处理ExportToExcel必须。否则引发HttpException
        public override void VerifyRenderingInServerForm(Control control)
        { }
    }
}